package com.spzx.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.IPaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 付款信息表 服务实现类
 * </p>
 *
 * @author xiongkunYang
 * @since 2025/06/03 08:42
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String content) {
        // 防止重复提交：如果支付信息已存在则直接结束
        String orderNo = orderInfo.getOrderNo();
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        if(paymentInfo != null) {
            return;
        }

        paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(SecurityUtils.getUserId());
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayType(2);
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        paymentInfo.setContent(content);
        paymentInfo.setPaymentStatus(0);
        String username = SecurityUtils.getUsername();
        paymentInfo.setCreateBy(username);
        paymentInfo.setUpdateBy(username);
        this.save(paymentInfo);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updatePaymentStatus(PaymentInfo paymentInfo, Map<String, String> paramMap) {
        //更新支付信息
        paymentInfo.setPayType(2);
        paymentInfo.setPaymentStatus(1);
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));
        this.updateById(paymentInfo);
    }
}
